<?php
/*------------------------------------------------------ */
//-- 微信
//-- Author: iqgmy
/*------------------------------------------------------ */
namespace app\weixin\controller\api;
use app\ApiController;

use app\weixin\model\WeiXinUsersModel;
use app\weixin\model\WeiXinModel;
use app\weixin\model\WeiXinMpModel;
use app\weixin\model\WeiXinInviteLogModel;
use app\weixin\model\WeiXinAccessTokenModel;
use app\member\model\UsersModel;
use think\Db;
use think\facade\Cache;
use think\facade\Log;

class Index  extends ApiController{

    public function initialize(){
        parent::initialize();
        $this->Model = new WeiXinUsersModel();
    }

    /*------------------------------------------------------ */
    //--  获取微信小程序/公众号的openId
    /*------------------------------------------------------ */
    public function getOpenId(){
        $code = input('code','','trim');
        $type = input('type','','trim');

        if ($type == 'MP'){
            $is_mp = 1;
            $res = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.settings('xcx_appid').'&secret='.settings('xcx_appsecret').'&js_code='.$code.'&grant_type=authorization_co');
            Log::info("用户信息==".$res);
            $wxModel = new WeiXinMpModel();
            $data = json_decode($res,true);
            if(!isset($data['openid'])){
                $openid = input('openid','','trim');
                $data['openid'] = $openid;
            }

            $where[] = ['wx_openid','=',$data['openid']];
            $where[] = ['is_mp','=',$is_mp];
            $wxuInfo = $this->Model->where($where)->find();
            if (empty($wxuInfo)){//数据不存在，写入
                $inData['is_mp'] = $is_mp;
                $inData['wx_openid'] = $data['openid'];
                $inData['session_key'] = $data['session_key'];
                $this->Model->save($inData);
            }else{
                $this->Model->where($where)->update(['session_key' => $data['session_key']]);
            }

            return $this->success($data);
        }else{
            $is_mp = 0;
            $res = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" .settings('weixin_appid') . "&secret=" .settings('weixin_appsecret') . "&code=" . $code . "&grant_type=authorization_code");
            $data = json_decode($res,true);
            (new WeiXinAccessTokenModel)->saveUserAccessToken($data);
            $wxModel = new WeiXinModel();
        }

        if (empty($data['openid'])){
            return $this->error($data['errcode'].'-'.$data['errmsg']);
        }
        $unInfo = [];
        if (empty($data['unionid']) == false){//存在unionid，查询是否已存在相关公众号会员数据
            $unInfo = $this->Model->where('unionid',$data['unionid'])->find();
        }
        $where[] = ['wx_openid','=',$data['openid']];
        $where[] = ['is_mp','=',$is_mp];
        $wxuInfo = $this->Model->where($where)->find();
        if (empty($wxuInfo)){//数据不存在，写入
            $inData['is_mp'] = $is_mp;
            $inData['wx_openid'] = $data['openid'];
            if (empty($data['unionid']) == false){
                $inData['unionid'] = $data['unionid'];
            }
            $inData['add_time'] = time();
            if (empty($unInfo) == false){
                $inData['user_id'] = $unInfo['user_id'];
            }

            $wxUserInfo = $wxModel->getWxUserInfo($inData['wx_openid']);
            Log::info("用户头像222==".json_encode($wxUserInfo));
            $inData['sex'] = $wxUserInfo['sex'];
            $inData['subscribe'] = $wxUserInfo['subscribe'] * 1;
            $inData['wx_nickname'] = $wxUserInfo['nickname'];
            $inData['wx_headimgurl'] = $wxUserInfo['headimgurl'];
            $inData['wx_city'] = $wxUserInfo['city'];
            $inData['wx_province'] = $wxUserInfo['province'];
            $this->Model->save($inData);
            $wxuInfo = $this->Model->where($where)->find();
        }else{
            //未知是否有坑，理论上只会从无到冇，不应该存在A变B
            if ($wxuInfo['unionid'] != $data['unionid']){
                $upData['unionid'] = $data['unionid'];
            }
            //如果小程序未产生会员，公众号已存在关联会员，直接更新小程序对应的会员
            if ($wxuInfo['user_id'] == 0 && $unInfo['user_id'] > 0){
                $upData['user_id'] = $unInfo['user_id'];
            }
        }



        // if ($wxuInfo['update_time'] < time() - 86400 ){
//            $wxArr = $wxModel->getWxUserInfoSubscribe($wxuInfo['wx_openid']);
//            if ($wxArr['subscribe'] == 1){
//                $upData['sex'] = $wxArr['sex'];
//                $upData['subscribe'] = $wxArr['subscribe'] * 1;
//                $upData['wx_nickname'] = $wxArr['nickname'];
//                $upData['wx_headimgurl'] = $wxArr['headimgurl'];
//                $upData['wx_city'] = $wxArr['city'];
//                $upData['wx_province'] = $wxArr['province'];
//            }else{
//                $upData['subscribe'] = 0;
//            }
//            $upData['update_time'] = time();
        // }

        if (empty($data['session_key']) == false){
            $upData['session_key'] = $data['session_key'];
            unset($data['session_key']);
        }

        if (empty($upData) == false){
            $this->Model->where('wxuid',$wxuInfo['wxuid'])->update($upData);
        }

        if ($wxuInfo['user_id'] < 1){
            $share_token = input('share_token', '', 'trim');
            $UsersModel = new UsersModel();
            $wxlog['user_id'] = 0;
            if (empty($share_token) == false){
                $WeiXinInviteLogModel = new WeiXinInviteLogModel();
                $_share_token = $WeiXinInviteLogModel->where('wxuid',$wxuInfo['wxuid'])->order('id DESC')->value('share_token');
                if ($_share_token != $share_token){
                    $wxlog['wxuid'] = $wxuInfo['wxuid'];
                    $wxlog['user_id'] =  $UsersModel->getShareUser($share_token);
                    $wxlog['share_token'] = $share_token;
                    $wxlog['add_time'] = time();
                    $WeiXinInviteLogModel->save($wxlog);
                }
            }
            $inArr = [];
            if($is_mp){
                $inArr['nick_name'] = '';
                $inArr['headimgurl'] = './static/public/images/headimgurl.jpg';
                $inArr['sex'] = 1;
            }else{
                $inArr['nick_name'] = $wxuInfo['wx_nickname'];
                $inArr['headimgurl'] = $UsersModel->getHeadImg($wxuInfo['wx_headimgurl']);
                $inArr['sex'] = $wxuInfo['sex'];
            }
            $inArr['pid'] = $wxlog['user_id'];
            $inArr['invite_code'] = $wxlog['user_id'];
//            if (settings('register_status') == 2) {
            $res = $UsersModel->register($inArr,$wxuInfo['wxuid']);
            if (true !== $res) {
                return $this->error($res);
            }
            $user_id = $this->Model->where('wxuid',$wxuInfo['wxuid'])->value('user_id');
            $res = $UsersModel->doLogin($user_id);
            $data['token'] = $res;

//            }

        }else{
//            if (settings('register_status') == 2) {
            $user_id = $wxuInfo['user_id'];
            $res = (new UsersModel)->doLogin($wxuInfo['user_id']);
            $data['token'] = $res;
//            }
        }
        if($user_id){
            $data['nickname'] = (new UsersModel)->where(['user_id' => $user_id])->value('nick_name');
            $data['user_id'] = $user_id;
            $data['mobile'] = (new UsersModel)->where(['user_id' => $user_id])->value('mobile');
            $data['user_token'] = (new UsersModel)->where(['user_id' => $user_id])->value('token');
            $pid = (new UsersModel)->where(['user_id' => $user_id])->value('pid');
            (new UsersModel())->regUserBind($user_id,$pid,true);
        }
        return $this->success($data);
    }

    /**
     * [do_login 小程序自动授权注册登录]
     */
    public function do_login()
    {
        $openid = input('openid','','trim');
        $return['code'] = 1;
        if (empty($openid)) {
            $return['code'] = 0;
            $return['msg'] = '登录失败';
            return $this->ajaxReturn($return);
        }
        $wxuInfo = input('userInfo');
        //$wxuInfo['nickName']="张三";
        //return json_encode($wxuInfo);
        $share_token = input('share_token','','trim');
        $res = $this->Model->login($openid,$wxuInfo,$share_token);
        if ($res['code'] == 1) {
            $return['token'] = $res['token'];
            $return['is_bind'] = $res['is_bind'];
            return $this->ajaxReturn($return);
        }else{
            $return['code'] = 0;
            $return['msg'] = '登录失败';
            return $this->ajaxReturn($return);
        }
    }
    /*------------------------------------------------------ */
    //--  微信小程序手机号码登陆
    /*------------------------------------------------------ */
    public function loginByMpPhone(){
        $openid = input('openid','','trim');
        $iv = input('iv','','trim');
        $session_key = input('session_key','','trim');
        $encryptedData = input('encryptedData','','trim');
        $dataObj = $this->Model->WXBizDataCrypt($openid,$iv,$encryptedData,$session_key);

        if (is_array($dataObj) == false){
            return $this->error($dataObj);
        }
        $wxuInfo = $this->Model->where('wx_openid',$openid)->find();
        if (empty($wxuInfo)){//数据不存在，写入
            $inData['is_mp'] = 1;
            $inData['wx_openid'] = $openid;
            $this->Model->save($inData);
            $wxuInfo = $this->Model->where('wx_openid',$openid)->find();
        }
        $wxuser = $this->Model->where('wx_openid',$openid)->find();
        if ($wxuser['user_id'] <= 0) {
            $share_token = input('share_token', '', 'trim');
            $UsersModel = new UsersModel();

            $inArr['nick_name'] = '';
            $inArr['headimgurl'] = './static/public/images/headimgurl.jpg';
            $inArr['sex'] = 1;

            $inArr['pid'] = $UsersModel->getShareUser($share_token);
            $inArr['invite_code'] = $UsersModel->getShareUser($share_token);
//            if (settings('register_status') == 2) {
            $res = $UsersModel->register($inArr,$wxuInfo['wxuid']);
            if (true !== $res) {
                return $this->error($res);
            }
            $wxuser = $this->Model->where('wx_openid',$openid)->find();
        }

        $UsersModel = new UsersModel();
//        if($old_user = $UsersModel->where('mobile',$dataObj['phoneNumber'])->find()){
//            $this->Model->where('wx_openid',$openid)->update(['user_id' => $old_user['user_id']]);
//            $UsersModel->where('user_id',$wxuser['user_id'])->delete();
//            $return['token'] = $UsersModel->doLogin($old_user['user_id']);
//        }else{
//            $info = $UsersModel->lock(true)->where('user_id',$wxuser['user_id'])->find();
//            if (empty($info['mobile'])) {
//                $res = $UsersModel->where('user_id',$wxuser['user_id'])->update(['mobile'=>$dataObj['phoneNumber']]);
//                $UsersModel->cleanMemcache($wxuser['user_id']);
//                if ($res <= 0) {
//                    $return['code'] = 0;
//                    $return['msg'] = '授权失败';
//                    return $this->ajaxReturn($return);
//                }
//            }
//        }
        $user =  Db::name('users')->where('user_id',$wxuser['user_id'])->find();
        Db::name('users')->where('user_id',$wxuser['user_id'])->update(['mobile'=>$dataObj['phoneNumber']]);
        $return['code'] = 1;
        $return['token'] = $UsersModel->doLogin($wxuser['user_id']);
        $return['nickname'] = $user['nick_name'];
        $return['openid'] = $openid;
        $return['user_id'] = $wxuser['user_id'];
        $return['user_token'] = $user['token'];
        return $this->success($return);
    }

}?>
